#!/usr/bin/env bash

# utility function to download a file
function download {
  if [ -x "$(command -v wget)" ]; then
    wget -c -O "$2" "$1"
  elif [ -x "$(command -v curl)" ]; then
    curl -L "$1" >"$2"
  else
    echo "Can't figure out how to download from web.  Please install wget or curl." >&2
    exit 1
  fi
}

CVC_DIR=$(dirname $(dirname "$0"))
mkdir -p $CVC_DIR/deps
pushd $CVC_DIR/deps

BASE_DIR=`pwd`
mkdir -p $BASE_DIR/tmp/

##### ALFC
ALFC_DIR="$BASE_DIR/alf-checker"
mkdir -p $ALFC_DIR

# download and unpack ALFC
ALF_VERSION="eca2cbd4e27712c35a9111a3c9c517f49c593500"
download "https://github.com/cvc5/alfc/archive/$ALF_VERSION.tar.gz" $BASE_DIR/tmp/alfc.tgz
tar --strip 1 -xzf $BASE_DIR/tmp/alfc.tgz -C $ALFC_DIR

# build and install ALFC
pushd $ALFC_DIR
mkdir -p build && cd build
cmake -DCMAKE_INSTALL_PREFIX="$BASE_DIR" ..
make -j$(nproc)
mkdir -p $BASE_DIR/bin
cp ./src/alfc $BASE_DIR/bin/alfc
popd

##### signatures

# The ALFC signatures live in the main cvc5 repository. We reference this
# directory in the include command generated by the script below.
SIG_DIR="$CVC_DIR/proofs/alf/cvc5"

# install scripts
cat << EOF > $BASE_DIR/bin/alfc_gen_and_check.sh
#!/usr/bin/env bash

echo "=== Generate proof: \$@"
$BASE_DIR/bin/alfc_gen.sh \$@ > alfc.proof.smt3

echo "=== Check proof with ALFC"
$BASE_DIR/bin/alfc_check.sh alfc.proof.smt3
EOF
chmod +x $BASE_DIR/bin/alfc_gen_and_check.sh

cat << EOF > $BASE_DIR/bin/alfc_gen.sh
#!/usr/bin/env bash

# call cvc5 and remove the first line of the output (should be "unsat")
echo "(include \"$SIG_DIR/Cvc5.smt3\")"
\$@ --dump-proofs --proof-format=alf --proof-granularity=theory-rewrite | tail -n +2
EOF
chmod +x $BASE_DIR/bin/alfc_gen.sh

cat << EOF > $BASE_DIR/bin/alfc_check.sh
#!/usr/bin/env bash

cat \$@ | grep WARNING
CHECK=\$(cat \$@ | grep "step\|assume")
[ -z "\$CHECK" ] && echo "; WARNING: Empty proof"

$BASE_DIR/bin/alfc \$@

EOF
chmod +x $BASE_DIR/bin/alfc_check.sh

popd

echo ""
echo "========== How to use ALFC =========="
echo "Generate a ALFC proof with cvc5:"
echo "  $CVC_DIR/deps/bin/alfc_gen.sh cvc5 <options> <input file>"
echo "Check a generated proof:"
echo "  $CVC_DIR/deps/bin/alfc_check.sh <proof file>"
echo "Run cvc5 and check the generated proof:"
echo "  $CVC_DIR/deps/bin/alfc_gen_and_check.sh cvc5 <options> <input file>"
